<?php
//error_reporting(E_ALL);
//ini_set( "display_errors", "ON" );
require "db/connect.php";
require "functions/security.php";

$records = array();

if(!empty($_POST)){ var_dump($_POST);
    if(isset($_POST["first_name"], $_POST["last_name"], $_POST["bio"])) {

        $first_name=trim($_POST["first_name"]);
        $last_name=trim($_POST["last_name"]);
        $bio=trim($_POST["bio"]);
        

            if(!empty($first_name) && !empty($last_name) && !empty($bio)) {
                $insert = $db->prepare("INSERT INTO people(first_name, last_name, bio, created) VALUES (?, ?, ?, NOW())");
                $insert->bind_param("sss", $first_name, $last_name, $bio);
                
                if($insert->execute()) {
                    header("Location: example_app.php");
                    die();
                }
        }
    }
}

if($results = $db->query("SELECT * FROM people")){
    if($results->num_rows){
        while($row = $results->fetch_object()){
            $records[] = $row;
        }
        $results->free();
    }
}

//echo '<pre>', print_r($records), '</pre>';

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>People</title>
</head>
<body>
    <h3>People</h3>  

    <?php 
    if(!count($records)){
        echo "No records";
    } else {
    ?>

            <table>
                <thead>
                    <tr>
                        <th>First name</th>
                        <th>Last name</th>
                        <th>Bio</th>
                        <th>Created</th>
                    </tr>
                </thead>

                <tbody>
                    <?php
                    foreach($records as $r) {
                    ?>
                            <tr>
                                <td><?php echo escape($r->first_name); ?></td>
                                <td><?php echo escape($r->last_name); ?></td>
                                <td><?php echo escape($r->bio); ?></td>
                                <td><?php echo escape($r->created); ?></td>
                            </tr>
                    <?php } ?>
                </tbody>
            </table>
    <?php } ?>

    <hr>

<form action="" method="post">
    <div class="field">
        <label for="first_name">First_name</label>
        <input id="first_name" type="text" name="first_name" autocomplete="off">
    </div>
    <div class="field">
        <label for="last_name">Last_name</label>
        <input id="last_name" type="text" name="last_name" autocomplete="off">
    </div>
    <div class="field">
        <label for="bio">Bio</label>
        <textarea id="bio" name="bio" cols="30" rows="5"></textarea>
    </div>
    <input type="submit" value="INSERT">
</form>



    
</body>
</html>

